package cn.zk;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ConnectionWatcher implements Watcher{

    private static final int SESSION_TIMEOUT = 5000;

    protected ZooKeeper zk;
    private CountDownLatch connectionSignal = new CountDownLatch(1);

    public void connect(String hosts) throws InterruptedException, IOException {
        zk = new ZooKeeper(hosts,SESSION_TIMEOUT,this);
        connectionSignal.await();
    }

    public void process(WatchedEvent watchedEvent) {
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            connectionSignal.countDown();
        }
    }

    public void close() throws InterruptedException {
        zk.close();
    }


}
